package thread.unit2.learntsafe;

/**
 * 使用同步块 解决继承实现多线程的线程安全问题
 */

public class ThreadSafeDemo2 extends Thread{
    //实例的对象可以共享静态资源
    private static int ticket = 100;

    private static Object object = new Object();

    public static void main(String[] args) {
        ThreadSafeDemo2 t1 = new ThreadSafeDemo2();
        ThreadSafeDemo2 t2 = new ThreadSafeDemo2();
        ThreadSafeDemo2 t3 = new ThreadSafeDemo2();

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();

    }

    @Override
    public void run() {
        while(true){
            synchronized (ThreadSafeDemo2.class){//Class clazz = ThreadP2.class -->放回一个Class类型的对象
//            synchronized (object) { //该方式同步失败，锁不是唯一的
                if (ticket > 0) {
                    try {
                        sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "卖票；票号为：" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }
        }
    }
}
